package com.reebake.ideal.security.oauth2.client;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.reebake.ideal.json.util.JsonUtil;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;

import java.util.List;
import java.util.Map;

public class SmartOauth2UserService extends DefaultOAuth2UserService {

	@Override
	public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
		AuthUser authUser = (AuthUser) userRequest.getAdditionalParameters().get(OAuth2ParameterNames.USER_CODE);
		List<GrantedAuthority> grantedAuthorities = CollectionUtil.newArrayList();
		for (String scope : userRequest.getClientRegistration().getScopes()) {
			grantedAuthorities.add(new SimpleGrantedAuthority(scope));
		}
		Map<String, Object> attributes = JsonUtil.toBean(JsonUtil.toJsonStr(authUser), new TypeReference<Map<String, Object>>() {
		});

        return new DefaultOAuth2User(grantedAuthorities, attributes, LambdaUtil.getFieldName(AuthUser::getUuid));
	}

}
